<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no"/>
    <title>14-父子组件传值</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>
<body>
<div id="app" v-cloak></div>
<script src="js/vue.js"></script>
<script>
    //子组件
    let ChildrenComponent = {
        template: `
            <div>
                我是子组件,父组件的值：{{title}},{{save}}<br/>
                <button type="button" @click="sendParent()">子组件给父组件传值</button>
            </div>
        `,
        //接收方式一
        // props:['title','save'],
        //接收方式二（推荐）
        props: {
            title: {
                type: String,//类型
                required: true//是否为必传 true:是，false：否
            },
            save: {
                type: String,
                required: false
            }
        },
        methods: {
            sendParent() {
                this.$emit("getChildren", "我是子组件传过来的值");
            }
        }
    };

    //父组件
    let ParentComponent = {
        template: `
            <div>
                我是父组件<br/>
                <ChildrenComponent title="我是父组件传过来的值" save="保存" @getChildren="getChildVal($event)"></ChildrenComponent>
                {{childrenVal}}
            </div>
        `,
        data() {
            return {
                childrenVal: ""
            }
        },
        components: {
            ChildrenComponent
        },
        methods: {
            getChildVal(val) {
                console.log(val);
                this.childrenVal = val;
            }
        }
    };

    //入口组件
    let App = {
        template: `
            <div>
                <ParentComponent></ParentComponent>
            </div>
        `,
        //局部组件注册方式
        components: {
            ParentComponent
        }
    };
    new Vue({
        el: "#app",
        template: `
            <App></App>
        `,
        components: {
            App
        }
    })
</script>
</body>
</html>
